// 游戏常量
const BOARD_SIZE = 15; // 15x15的棋盘

// 游戏状态
let gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0)); // 0: 空, 1: 黑, 2: 白
let currentPlayer = 1; // 1: 黑方, 2: 白方
let gameOver = false;

// 自适应变量
let cellSize; // 每个格子的大小
let canvasSize; // 画布大小
let scale = 1; // 缩放比例

// 获取DOM元素
const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
const statusElement = document.getElementById('status');
const restartButton = document.getElementById('restartBtn');
const gameBoardElement = document.querySelector('.game-board');

// 计算自适应的棋盘大小
function calculateBoardSize() {
    // 获取可用空间
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const containerPadding = 40; // 容器内边距
    const infoHeight = 150; // 信息区域高度
    
    // 根据屏幕方向计算可用尺寸
    let availableWidth = windowWidth - containerPadding;
    let availableHeight = windowHeight - containerPadding - infoHeight;
    
    // 取较小值作为基准
    const availableSize = Math.min(availableWidth, availableHeight);
    
    // 计算格子大小，确保棋盘在屏幕内且有足够的触摸区域
    cellSize = Math.floor((availableSize - 20) / (BOARD_SIZE - 1));
    // 限制最小和最大格子大小
    cellSize = Math.min(Math.max(cellSize, 20), 40);
    
    canvasSize = cellSize * (BOARD_SIZE - 1);
    
    // 设置画布大小
    canvas.width = canvasSize;
    canvas.height = canvasSize;
    
    // 更新canvas样式
    canvas.style.width = canvasSize + 'px';
    canvas.style.height = canvasSize + 'px';
}

// 初始化游戏
function initGame() {
    // 重置游戏状态
    gameBoard = Array(BOARD_SIZE).fill().map(() => Array(BOARD_SIZE).fill(0));
    currentPlayer = 1;
    gameOver = false;
    statusElement.textContent = '游戏开始，请黑方落子';
    
    // 计算棋盘大小
    calculateBoardSize();
    
    // 绘制棋盘
    drawBoard();
}

// 绘制棋盘
function drawBoard() {
    // 清空画布
    ctx.clearRect(0, 0, canvasSize, canvasSize);
    
    // 根据屏幕大小调整线条粗细
    const lineWidth = cellSize > 30 ? 2 : 1;
    
    // 设置线条样式
    ctx.strokeStyle = '#000';
    ctx.lineWidth = lineWidth;
    
    // 绘制横线和竖线
    for (let i = 0; i < BOARD_SIZE; i++) {
        // 横线
        ctx.beginPath();
        ctx.moveTo(0, i * cellSize);
        ctx.lineTo(canvasSize, i * cellSize);
        ctx.stroke();
        
        // 竖线
        ctx.beginPath();
        ctx.moveTo(i * cellSize, 0);
        ctx.lineTo(i * cellSize, canvasSize);
        ctx.stroke();
    }
    
    // 绘制五个星位点，根据格子大小调整星点大小
    const starRadius = Math.max(3, Math.floor(cellSize / 10));
    const starPoints = [
        {x: 3, y: 3}, 
        {x: 11, y: 3}, 
        {x: 7, y: 7}, 
        {x: 3, y: 11}, 
        {x: 11, y: 11}
    ];
    
    starPoints.forEach(point => {
        drawCircle(point.x * cellSize, point.y * cellSize, starRadius, '#000');
    });
    
    // 绘制所有棋子，根据格子大小调整棋子大小
    const stoneRadius = cellSize / 2 - 3;
    for (let row = 0; row < BOARD_SIZE; row++) {
        for (let col = 0; col < BOARD_SIZE; col++) {
            if (gameBoard[row][col] === 1) {
                drawCircle(col * cellSize, row * cellSize, stoneRadius, '#000');
            } else if (gameBoard[row][col] === 2) {
                drawCircle(col * cellSize, row * cellSize, stoneRadius, '#fff', true);
                // 为白棋添加一个轻微的阴影，使其在浅色背景上更明显
                ctx.strokeStyle = '#aaa';
                ctx.lineWidth = 1;
                ctx.stroke();
            }
        }
    }
}

// 绘制圆形
function drawCircle(x, y, radius, color, stroke = false) {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.fillStyle = color;
    ctx.fill();
    if (stroke) {
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 1;
        ctx.stroke();
    }
}

// 获取触摸/点击位置对应的棋盘坐标
function getBoardPosition(event) {
    const rect = canvas.getBoundingClientRect();
    let x, y;
    
    // 处理触摸事件
    if (event.touches && event.touches.length > 0) {
        x = event.touches[0].clientX - rect.left;
        y = event.touches[0].clientY - rect.top;
    } else {
        // 处理鼠标事件
        x = event.clientX - rect.left;
        y = event.clientY - rect.top;
    }
    
    // 计算缩放比例
    const scaleX = canvasSize / rect.width;
    const scaleY = canvasSize / rect.height;
    
    // 根据缩放比例调整坐标
    const scaledX = x * scaleX;
    const scaledY = y * scaleY;
    
    // 计算最近的交叉点
    const col = Math.round(scaledX / cellSize);
    const row = Math.round(scaledY / cellSize);
    
    // 检查是否在棋盘范围内
    if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
        return {row, col};
    }
    
    return null;
}

// 落子
function placeStone(row, col) {
    // 检查位置是否为空且游戏未结束
    if (gameBoard[row][col] === 0 && !gameOver) {
        gameBoard[row][col] = currentPlayer;
        drawBoard();
        
        // 检查是否获胜
        if (checkWin(row, col)) {
            gameOver = true;
            const playerName = currentPlayer === 1 ? '黑方' : '白方';
            statusElement.textContent = `${playerName}获胜！点击重新开始按钮继续游戏`;
            return;
        }
        
        // 切换玩家
        currentPlayer = currentPlayer === 1 ? 2 : 1;
        const nextPlayerName = currentPlayer === 1 ? '黑方' : '白方';
        statusElement.textContent = `${nextPlayerName}回合，请落子`;
    }
}

// 检查是否获胜
function checkWin(row, col) {
    const directions = [
        [0, 1],  // 水平
        [1, 0],  // 垂直
        [1, 1],  // 对角线
        [1, -1]  // 反对角线
    ];
    
    const player = gameBoard[row][col];
    
    for (const [dx, dy] of directions) {
        let count = 1; // 当前位置已经有一个棋子
        
        // 正方向检查
        for (let i = 1; i < 5; i++) {
            const newRow = row + i * dx;
            const newCol = col + i * dy;
            
            if (newRow >= 0 && newRow < BOARD_SIZE && 
                newCol >= 0 && newCol < BOARD_SIZE && 
                gameBoard[newRow][newCol] === player) {
                count++;
            } else {
                break;
            }
        }
        
        // 反方向检查
        for (let i = 1; i < 5; i++) {
            const newRow = row - i * dx;
            const newCol = col - i * dy;
            
            if (newRow >= 0 && newRow < BOARD_SIZE && 
                newCol >= 0 && newCol < BOARD_SIZE && 
                gameBoard[newRow][newCol] === player) {
                count++;
            } else {
                break;
            }
        }
        
        // 五子连珠
        if (count >= 5) {
            return true;
        }
    }
    
    return false;
}

// 事件监听
canvas.addEventListener('click', (event) => {
    const pos = getBoardPosition(event);
    if (pos) {
        placeStone(pos.row, pos.col);
    }
});

// 触摸屏支持 - 优化触摸体验
canvas.addEventListener('touchstart', (event) => {
    event.preventDefault(); // 防止页面滚动和缩放
    const pos = getBoardPosition(event);
    if (pos) {
        placeStone(pos.row, pos.col);
    }
});

// 处理屏幕旋转和尺寸变化
window.addEventListener('resize', () => {
    const tempBoard = JSON.parse(JSON.stringify(gameBoard)); // 保存当前棋盘状态
    const tempPlayer = currentPlayer;
    const tempGameOver = gameOver;
    const tempStatus = statusElement.textContent;
    
    calculateBoardSize();
    
    // 恢复棋盘状态
    gameBoard = tempBoard;
    currentPlayer = tempPlayer;
    gameOver = tempGameOver;
    statusElement.textContent = tempStatus;
    
    drawBoard();
});

// 处理方向变化
window.addEventListener('orientationchange', () => {
    // 短暂延迟以确保方向变化完成
    setTimeout(() => {
        const tempBoard = JSON.parse(JSON.stringify(gameBoard)); // 保存当前棋盘状态
        const tempPlayer = currentPlayer;
        const tempGameOver = gameOver;
        const tempStatus = statusElement.textContent;
        
        calculateBoardSize();
        
        // 恢复棋盘状态
        gameBoard = tempBoard;
        currentPlayer = tempPlayer;
        gameOver = tempGameOver;
        statusElement.textContent = tempStatus;
        
        drawBoard();
    }, 300);
});

// 重新开始按钮
restartButton.addEventListener('click', initGame);

// 初始化游戏
window.onload = () => {
    // 确保在页面完全加载后初始化
    setTimeout(initGame, 100);
};